//
//  AppDelegate.m
//  TakeYouTourTogether
//
//  Created by king on 15/11/26.
//  Copyright © 2015年 king. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideViewController.h"
#import "XGPush.h"
#import "WeiboSDK.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "ExchangeRateConvert.h"
@interface AppDelegate ()<WeiboSDKDelegate, QQApiInterfaceDelegate>

@property (nonatomic ,strong)BMKMapManager *mapManager;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
//
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"LNsk2y3TsTw4NDiCBL7YPGsl" generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:@"2172439015"];
    
    // 1.注册
    // 系统版本判断
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f) {
        // 系统iOS8.0以上使用
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert categories:nil]];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
    } else {
        // iOS8.0以下
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeAlert];
    }
    [XGPush startApp:2200169344 appKey:@"5112f2168e6647aa2a8de0f7d8addaec"];
    
    [[JSMHistoryTool historyBaseHandle] openDB];
    [[JSMHistoryTool historyBaseHandle] createTable];
    /**
     *  收藏
     */
    [SaveTool isHaveModelFolder];
    NSLog(@"***%@",NSHomeDirectory());
    [ReadCacheTool isHaveFilder];
    // 创建tabbarItems
    [self createTabbarItems];

    
    
    return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if ([[url absoluteString] hasPrefix:@"tencent"]) {
        return [QQApiInterface handleOpenURL:url delegate:self];
    } else if ([[url absoluteString] hasPrefix:@"wb"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }
    return NO;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    if ([[url absoluteString] hasPrefix:@"tencent"]) {
        
        return [TencentOAuth HandleOpenURL:url];
        
    }else if([[url absoluteString] hasPrefix:@"wb"]) {
        
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else {
        return NO;
    }
}
#pragma mark - 实现代理回调
/**
 *  微博
 *
 *  @param response 响应体。根据 WeiboSDKResponseStatusCode 作对应的处理.
 *  具体参见 `WeiboSDKResponseStatusCode` 枚举.
 */

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    NSString *message;
    switch (response.statusCode) {
        case WeiboSDKResponseStatusCodeSuccess:
            message = @"分享成功";
            break;
        case WeiboSDKResponseStatusCodeUserCancel:
            message = @"取消分享";
            break;
        case WeiboSDKResponseStatusCodeSentFail:
            message = @"分享失败";
            break;
        default:
            message = @"分享失败";
            break;
    }
    //    showAlert(message);
    //    UIAlertController *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:_msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
}

/**
 *  处理来至QQ的请求
 *
 *  @param req QQApi请求消息基类
 */
- (void)onReq:(QQBaseReq *)req
{
    
}

/**
 *  处理来至QQ的响应
 *
 *  @param resp 响应体，根据响应结果作对应处理
 */
- (void)onResp:(QQBaseResp *)resp
{
    NSString *message;
    if([resp.result integerValue] == 0) {
        message = @"分享成功";
    }else{
        message = @"分享失败";
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
}

// 注册失败返回一个error
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"error ======== %@", error);
}
// 5. 发送通知成功返回通知内容
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"userInfo ==== %@", userInfo);
}
// 2. 注册成功APNS返回Token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 3. 将获得的Token发给自己的服务器
    [XGPush registerDevice:deviceToken];
    NSLog(@"Token ======== %@", [deviceToken description]);
}


- (void)createTabbarItems {
    // 起程(乐游圈)
    JSMLeavingViewController *leavingController = [[JSMLeavingViewController alloc] init];
    UINavigationController *leavingNavcController = [[UINavigationController alloc] initWithRootViewController:leavingController];
    leavingNavcController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"起程" image:[UIImage imageNamed:@"iconfont-jinlingyingcaiwangtubiao98.png"] selectedImage:[UIImage imageNamed:TABBAR_SELECTED]];
    
    // 梦都市(发现)
    JSMDreamCityViewController *dreamCityController = [[JSMDreamCityViewController alloc] init];
    UINavigationController *dreamCityNavcController = [[UINavigationController alloc] initWithRootViewController:dreamCityController];
    dreamCityNavcController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"梦都市" image:[UIImage imageNamed:LEAVING_IMAGE] selectedImage:[UIImage imageNamed:TABBAR_SELECTED]];
    
    // 一起向(在途)
    JSMTouringViewController *touringController = [[JSMTouringViewController alloc] init];
    UINavigationController *touringNavcController = [[UINavigationController alloc] initWithRootViewController:touringController];
    touringNavcController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"一起向" image:[UIImage imageNamed:@"iconfont-xiangzuo.png"] selectedImage:[UIImage imageNamed:TABBAR_SELECTED]];
    
    // 带着你(后补 - 待定)
    JSMStrategyViewController *strategyController = [[JSMStrategyViewController alloc] init];
    UINavigationController *strategyNavcController = [[UINavigationController alloc] initWithRootViewController:strategyController];
    strategyNavcController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"带着你" image:[UIImage imageNamed:STRATEGY_IMAGE] selectedImage:[UIImage imageNamed:TABBAR_SELECTED]];
    
    // 我(个人中心)
    JSMMyViewController *myController = [[JSMMyViewController alloc] init];
    UINavigationController *myNavcController = [[UINavigationController alloc] initWithRootViewController:myController];
    myNavcController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我" image:[UIImage imageNamed:MY_IMAGE] selectedImage:[UIImage imageNamed:TABBAR_SELECTED]];
    
    // 创建tabbar
    UITabBarController *tabbarController = [[UITabBarController alloc] init];
    tabbarController.viewControllers = @[leavingNavcController, dreamCityNavcController, touringNavcController, strategyNavcController, myNavcController];
    tabbarController.tabBar.tintColor = [UIColor orangeColor];
    
    // 引导页
    void (^block)() = ^{
        self.window.rootViewController = tabbarController;
        [AFNIsnetWorkingTool sharedIsNetworking];

 };
    
    NSString *currentVersions = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *lastVersions = [[NSUserDefaults standardUserDefaults] valueForKey:@"CFBundleShortVersionString"];
    // 第一次登录
    [[ExchangeRateConvert shareExchangeRateConvert] openDB];
    if (![currentVersions isEqualToString:lastVersions] || !lastVersions) {
        [[NSUserDefaults standardUserDefaults] setValue:currentVersions forKey:@"CFBundleShortVersionString"];
        GuideViewController *guideView = [[GuideViewController alloc] init];
        self.window.rootViewController = guideView;
        guideView.block = block;
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isDayOrNight"];
        // 创建汇率换算路径文件 & 创建数据库 & 表
        [[ExchangeRateConvert shareExchangeRateConvert] createTableForExchangeRateConvert];
        
    // 第二次登录
    } else {
        self.window.rootViewController = tabbarController;
        [AFNIsnetWorkingTool isnetWorking];
    }
    [NightTimeModel shareNightTimeModel].isDayOrNight = [[NSUserDefaults standardUserDefaults] boolForKey:@"isDayOrNight"];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
